package com;

import java.awt.Container;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import javax.swing.JProgressBar;
import javax.swing.JTextField;

public class FileThreadCopy implements Runnable {
	File f;
	File fs;
	private JTextField tf1;
	private JTextField tf2;
	private JProgressBar pb;
	private Container container;

	public FileThreadCopy(JTextField tf1, JTextField tf2, JProgressBar pb,Container contaier) {
		this.tf1 = tf1;
		this.tf2 = tf2;
		this.pb = pb;
		this.container=container;
	}

	@SuppressWarnings("resource")
	public void run() {
		// TODO Auto-generated method stub
		f = new File(tf1.getText());
		fs = new File(tf2.getText());
		final double filenum = f.length();

		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {
			fis = new FileInputStream(f);
		} catch (FileNotFoundException e) {
            new Dialog(container, "未找到源文件！", "复制失败！");
            return;
		}

		try {
			fos = new FileOutputStream(fs);
		} catch (FileNotFoundException e) {
			new Dialog(container, "未找到目的文件！", "复制失败！");
			return;
		}

		byte[] buf = new byte[1024 * 8];
		int sum = 0;
		int b = 0;
		DecimalFormat df = new DecimalFormat("#00");

		while (b != -1) {
			try {
				b = fis.read(buf);
				System.out.println("读取：" + Thread.currentThread().getName() + ":  " + b);
			} catch (IOException e) {
				new Dialog(container, "文件读取时出错！！", "复制失败！");
				return;
			}

			sum += b;
			String s = df.format(sum / filenum * 100);
			pb.setValue(Integer.valueOf(s));
		}
		
		try {
			fos.write(buf);
		} catch (IOException e) {
			new Dialog(container, "文件写入时出错！", "复制失败！");
			return;
		}
		try {
			fis.close();
		} catch (IOException e1) {
			new Dialog(container, "文件读取关闭时时出错！", "复制失败！");
			return;
		}
		try {
			fos.flush();
		} catch (IOException e) {
			new Dialog(container, "文件写入关闭时出错！", "复制失败！");
			return;
		}
		
		new Dialog(container, "恭喜你！文件复制成功", "复制成功！");
	}
}
